const Router = require('koa-router')
const bcrypt = require('bcryptjs')
const { User, Role } = require('../models')
const { checkPermission } = require('../middleware/auth')

const router = new Router({ prefix: '/api/users' })

// 获取用户列表
router.get('/', checkPermission('user:read'), async (ctx) => {
  try {
    const { page = 1, pageSize = 10, email, status } = ctx.query
    
    const where = {}
    if (email) where.email = { [require('sequelize').Op.like]: `%${email}%` }
    if (status) where.status = status

    const { count, rows } = await User.findAndCountAll({
      where,
      include: [{
        model: Role,
        as: 'roles',
        through: { attributes: [] }
      }],
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize),
      order: [['created_at', 'DESC']]
    })

    ctx.body = {
      success: true,
      data: rows,
      total: count,
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    }
  } catch (error) {
    console.error('Get users error:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取用户列表失败'
    }
  }
})

// 创建用户
router.post('/', checkPermission('user:create'), async (ctx) => {
  try {
    const { username, password, email, realName, phone, roleIds, status } = ctx.request.body

    // 验证必填字段
    if (!username || !password || !email || !realName) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '必填字段不能为空'
      }
      return
    }

    // 检查用户名和邮箱是否已存在
    const existingUser = await User.findOne({
      where: {
        [require('sequelize').Op.or]: [
          { username },
          { email }
        ]
      }
    })

    if (existingUser) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '用户名或邮箱已存在'
      }
      return
    }

    // 密码加密
    const hashedPassword = await bcrypt.hash(password, parseInt(process.env.BCRYPT_ROUNDS) || 10)

    // 创建用户
    const user = await User.create({
      username,
      password: hashedPassword,
      email,
      real_name: realName,
      phone,
      status: status || 'active'
    })

    // 分配角色
    if (roleIds && roleIds.length > 0) {
      const roles = await Role.findAll({
        where: { id: roleIds }
      })
      await user.setRoles(roles)
    }

    ctx.body = {
      success: true,
      message: '用户创建成功',
      data: { id: user.id }
    }
  } catch (error) {
    console.error('Create user error:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '创建用户失败'
    }
  }
})

// 更新用户
router.put('/:id', checkPermission('user:update'), async (ctx) => {
  try {
    const { id } = ctx.params
    const { email, realName, phone, roleIds, status } = ctx.request.body

    const user = await User.findByPk(id)
    if (!user) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '用户不存在'
      }
      return
    }

    // 更新用户信息
    await user.update({
      email,
      real_name: realName,
      phone,
      status
    })

    // 更新角色
    if (roleIds) {
      const roles = await Role.findAll({
        where: { id: roleIds }
      })
      await user.setRoles(roles)
    }

    ctx.body = {
      success: true,
      message: '用户更新成功'
    }
  } catch (error) {
    console.error('Update user error:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '更新用户失败'
    }
  }
})

// 重置密码
router.post('/:id/reset-password', checkPermission('user:update'), async (ctx) => {
  try {
    const { id } = ctx.params
    const defaultPassword = '123456'

    const user = await User.findByPk(id)
    if (!user) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '用户不存在'
      }
      return
    }

    const hashedPassword = await bcrypt.hash(defaultPassword, parseInt(process.env.BCRYPT_ROUNDS) || 10)
    await user.update({ password: hashedPassword })

    ctx.body = {
      success: true,
      message: '密码重置成功'
    }
  } catch (error) {
    console.error('Reset password error:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '重置密码失败'
    }
  }
})

// 删除用户
router.delete('/:id', checkPermission('user:delete'), async (ctx) => {
  try {
    const { id } = ctx.params

    const user = await User.findByPk(id)
    if (!user) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '用户不存在'
      }
      return
    }

    // 不允许删除admin用户
    if (user.username === 'admin') {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '不能删除admin用户'
      }
      return
    }

    await user.destroy()

    ctx.body = {
      success: true,
      message: '用户删除成功'
    }
  } catch (error) {
    console.error('Delete user error:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '删除用户失败'
    }
  }
})

// 用户主题配置相关接口
router.get('/:userId/theme', checkPermission('user:read'), async (ctx) => {
  try {
    const { userId } = ctx.params
    const requestUserId = ctx.state.user.userId
    
    // 只允许用户查看自己的主题设置，或管理员查看其他用户的
    if (parseInt(userId) !== requestUserId && !ctx.state.user.permissions.includes('admin:all')) {
      ctx.status = 403
      ctx.body = {
        success: false,
        message: '无权限访问该用户的主题设置'
      }
      return
    }

    const { User } = require('../models')
    const user = await User.findByPk(userId)
    
    if (!user) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '用户不存在'
      }
      return
    }

    // 返回用户的主题配置，如果没有则返回默认配置
    const themeConfig = user.theme_config || {
      mode: 'dark',
      primaryColor: '#0ea5e9',
      accentColor: '#10b981',
      customColors: {
        purple: '#a855f7',
        cyan: '#00bfff',
        emerald: '#00ff88'
      }
    }

    ctx.body = {
      success: true,
      data: themeConfig,
      message: '获取主题配置成功'
    }
  } catch (error) {
    console.error('获取用户主题配置失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取主题配置失败',
      error: error.message
    }
  }
})

// 保存用户主题配置
router.put('/:userId/theme', checkPermission('user:update'), async (ctx) => {
  try {
    const { userId } = ctx.params
    const requestUserId = ctx.state.user.userId
    const themeConfig = ctx.request.body
    
    // 只允许用户修改自己的主题设置
    if (parseInt(userId) !== requestUserId && !ctx.state.user.permissions.includes('admin:all')) {
      ctx.status = 403
      ctx.body = {
        success: false,
        message: '无权限修改该用户的主题设置'
      }
      return
    }

    // 验证主题配置格式
    const validModes = ['light', 'dark', 'auto']
    if (!themeConfig.mode || !validModes.includes(themeConfig.mode)) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '无效的主题模式'
      }
      return
    }

    // 验证颜色格式（简单的hex颜色验证）
    const hexColorPattern = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/
    if (themeConfig.primaryColor && !hexColorPattern.test(themeConfig.primaryColor)) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '无效的主色调格式'
      }
      return
    }

    if (themeConfig.accentColor && !hexColorPattern.test(themeConfig.accentColor)) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '无效的辅助色格式'
      }
      return
    }

    const { User } = require('../models')
    const user = await User.findByPk(userId)
    
    if (!user) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '用户不存在'
      }
      return
    }

    // 更新用户的主题配置
    await user.update({
      theme_config: themeConfig,
      updated_at: new Date()
    })

    console.log(`✅ 用户 ${userId} 的主题配置已更新:`, themeConfig)

    ctx.body = {
      success: true,
      data: themeConfig,
      message: '主题配置已保存'
    }
  } catch (error) {
    console.error('保存用户主题配置失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '保存主题配置失败',
      error: error.message
    }
  }
})

module.exports = router